package process;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;

import android.R;
import android.content.res.Resources.Theme;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class SendFileUDP {
//	private String m_host = "10.0.2.2";
	private int m_port = 8282;
	
//	private String m_Path = "/sdcard";
	//private String m_filename = "b.ppt";
	private int size = 1400;
	private String m_Start = "SendFileName";
	private String m_Content = "SendContenFile";
	private String m_End = "Kết thúc";
	private InputStream is;
	private FileInputStream fis;
	private BufferedInputStream bis;
	private String g_m_Path;
	private String g_m_filename;
	String[]g_ArrayOfIP;
	SendAllFile send = new SendAllFile();
	private String tempIP;
	private int tempPort;
	private String m_Start2;
	private int num;
	// Khue has mod
	


public String SendUsingUDP(String m_Path ,String m_filename,String[] ArrayOfIP)
{
	
	String thongbao ="";
	SendAllFile send = new SendAllFile();
	int port = 8080;
	for(int i=0;i<ArrayOfIP.length;i++)
	{
		
	String m_host=ArrayOfIP[i];
	int kq = send.SendInfoStartSendUDP(m_host, m_port, m_Start);
	
//	int kq3 = send.sendInfoEndSend(m_host, i_port, m_End);
	if(kq==1)
	{
		
		//int ip = Integer.parseInt(m_host);
		//ServerSocket serverSocket;
		String line = "";
		try {
		 DatagramSocket serverSocket = new DatagramSocket(m_port);
			byte[] receiveData = new byte[1024];
			DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
			serverSocket.receive(receivePacket);

			//serverSocket = new ServerSocket(i_port);
			//Socket client = serverSocket.;
			line = new String(receivePacket.getData());
			// BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
	       // line=in.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 if(line.equals("OK"))
		 {
	
		int ports = 8181;
			int kq1 = send.sendfilename(m_host, ports, m_filename);
			
			if(kq1!=0)
			{
				int portss = 8383;
			//	int kq2 = send.SendfilenameUDP(m_host, i_port, m_Content);
				int kq3 = send.SenContentFile(m_Path, m_filename, m_host, portss);
				thongbao = "successful"+kq3;
				
			}
			else
			{
				thongbao = "unsuccessful";
			}
		 }
	}
	//}
	
	}
	return thongbao;
	
	
}
}

